package thread_pool_executor;

import java.util.concurrent.*;

/**
 * @author: 史大拿
 * @create: 2022-10-21 09:21
 * TODO
 **/
public class TPEClient2 {
    private static final int COUNT = 10;

    public static void main(String[] args) {
        // 只能存放100个任务
        LinkedBlockingQueue<Runnable> blockQueue = new LinkedBlockingQueue<>(10);

        ThreadPoolExecutor threadPoolExecutor =
                new ThreadPoolExecutor(
                        4, // 核心线程数
                        10, // 最大线程数
                        3, //
                        TimeUnit.SECONDS,
                        blockQueue,
                        new ThreadFactory() {
                            @Override
                            public Thread newThread(Runnable r) {
                                return new Thread(r);
                            }
                        });

        threadPoolExecutor.allowCoreThreadTimeOut(true);

        for (int i = 0; i < COUNT; i++) {
            int finalI = i;
            Runnable runnable = () -> {
                try {
                    Thread.sleep(2000);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    System.out.println("i:" + finalI + "\t线程:" + Thread.currentThread().getName());
                }
            };
            threadPoolExecutor.execute(runnable);
        }
    }
}
